package com.wtzz.police.base.controller;

import com.wtzz.police.base.bean.dto.*;
import com.wtzz.police.base.bean.req.ChangePwdDto;
import com.wtzz.police.base.bean.req.UserAddDto;
import com.wtzz.police.base.bean.req.UserFilterDto;
import com.wtzz.police.base.entity.User;
import com.wtzz.police.base.model.enums.Role;
import com.wtzz.police.base.model.enums.WtzzResponse;
import com.wtzz.police.base.model.response.PageWapper;
import com.wtzz.police.base.model.response.ResponseBean;
import com.wtzz.police.base.model.response.SingleResult;
import com.wtzz.police.base.service.UserService;
import com.wtzz.police.base.util.component.MapperWrapper;
import com.wtzz.police.base.model.annotaions.RoleCheck;
import com.wtzz.police.base.util.WebTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 用户Controller
 */
@Api(tags = "用户")
@RestController
@RequestMapping("user")
@Validated
public class UserController {

    @Autowired
    private UserService service;
    @Autowired
    private MapperWrapper mp;

    @PostMapping()
    @RoleCheck(Role.ADMIN)
    @ApiOperation(value = "新增用户(管理员权限)", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean addUser(
            @RequestBody
            @Validated
            @NotNull(message = "没提交数据")
            @ApiParam(value = "用户信息", type = "body")
                    UserAddDto userAddDto) {
        service.add(userAddDto);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @DeleteMapping({"{id}"})
    @RoleCheck(Role.ADMIN)
    @ApiOperation(value = "删除用户(管理员权限)")
    public ResponseBean<SingleResult<Boolean>> deleteUser(
            @PathVariable
            @NotBlank(message = "用户ID不能为空")
            @ApiParam(value = "用户ID", type = "path", required = true)
                    String id) {
        service.logicalDelete(id);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @PutMapping()
    @ApiOperation(value = "更新用户信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean updateUser(
            @RequestBody
            @Validated
            @NotNull(message = "没提交数据")
            @ApiParam(value = "用户信息", type = "body")
                    UserDto userDto) {
        User currentUser = WebTool.getCurrentUser();
        service.update(currentUser.getId(), userDto);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @PutMapping("{id}")
    @RoleCheck(Role.ADMIN)
    @ApiOperation(value = "更新用户信息(管理员权限)", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean updateUser(
            @PathVariable
            @NotBlank(message = "用户ID不能为空")
            @ApiParam(value = "用户Id", type = "path", required = true)
                    String id,
            @RequestBody
            @Validated
            @NotNull(message = "没提交数据")
            @ApiParam(value = "用户信息", type = "body")
                    UserDto userDto) {
        service.update(id, userDto);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @PutMapping({"{id}/enable"})
    @RoleCheck(Role.ADMIN)
    @ApiOperation(value = "禁用启用用户(管理员权限)")
    public ResponseBean<SingleResult<Boolean>> User(
            @PathVariable
            @NotBlank(message = "用户ID不能为空")
            @ApiParam(value = "用户Id", type = "path", required = true)
                    String id,
            @RequestParam
            @NotNull(message = "是否启用用户不能为空")
            @ApiParam(value = "是否启用用户", type = "query", required = true)
                    Boolean enable) {
        service.setEnabled(id, enable);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @PutMapping("password")
    @ApiOperation(value = "更改密码", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean changePassword(
            @RequestBody
            @Validated
            @ApiParam(value = "密码信息", type = "body")
                    ChangePwdDto changePwdDto) {
        service.changePassword(changePwdDto.getOldPassword(), changePwdDto.getNewPassword());
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @PutMapping("password/{id}")
    @RoleCheck(Role.ADMIN)
    @ApiOperation(value = "重置密码(管理员权限)")
    public ResponseBean resetPassword(
            @PathVariable
            @NotBlank(message = "用户ID不能为空")
            @ApiParam(value = "用户Id", type = "path", required = true)
                    String id) {
        service.resetPassword(id);
        return new ResponseBean<>(true, WtzzResponse.SUCCESS_OPTION);
    }

    @GetMapping("isNameExist")
    @ApiOperation(value = "用户名是否存在", notes = "新增用户时，需通过该接口判断用户是否存在！")
    public ResponseBean<SingleResult<Boolean>> existsUsername(@NotBlank(message = "用户名不能为空")
                                                              @ApiParam(value = "用户名", type = "query")
                                                                      String username) {
        return ResponseBean.of(SingleResult.of(!service.findByUsername(username).isPresent()));
    }

    @GetMapping("info")
    @ApiOperation("获取token用户信息")
    public ResponseBean<UserInfoDto> getUserInfo() {
        return ResponseBean.of(mp.map(WebTool.getCurrentUser(), UserInfoDto.class));
    }

    @PostMapping("list")
    @ApiOperation(value = "查询用户", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseBean<PageWapper<UserInfoDto>> listUser(
            @RequestBody
            @Validated
            @ApiParam(value = "查询条件", type = "body")
                    UserFilterDto userFilterDto) {
        if (userFilterDto.getFullname() != null) {
            userFilterDto.setFullname(userFilterDto.getFullname().trim());
        }
        if (userFilterDto.getUsername() != null) {
            userFilterDto.setUsername(userFilterDto.getUsername().trim());
        }
        Page<UserInfoDto> page = service.listNotDeleted(userFilterDto.createPageRequest(), userFilterDto);
        return new ResponseBean<>(true, new PageWapper<>(page));
    }

}
